package com.z100h.supplychain.evidence.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.config.Global;
import com.jeeplus.core.facade.FacadeException;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.core.service.ServiceException;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.z100h.supplychain.core.StockoutState;
import com.z100h.supplychain.evidence.entity.Stockout;
import com.z100h.supplychain.evidence.entity.StockoutSku;
import com.z100h.supplychain.evidence.mapper.StockoutMapper;
import com.z100h.supplychain.utils.HttpUtils;

/**
 * @author ZBH-001
 * @Title: StockoutService
 * @ProjectName supplychain
 * @Description: TODO
 * @date 2019/1/1717:59
 */
@Service
@Transactional(readOnly = true)
public class StockoutService extends CrudService<StockoutMapper, Stockout> {

	// private final static String URL = "http://192.168.199.199:8080/lehome";
	// private final static String URL = "http://218.2.197.230:8089/lehome";
	private static final Logger logger = LoggerFactory.getLogger(StockoutService.class);

	@Autowired
	private StockoutMapper stockoutMapper;

	@Autowired
	private StockoutSkuService stockoutSkuService;

	@Override
	public Stockout get(String id) {
		return super.get(id);
	}

	@Override
	public List<Stockout> findList(Stockout stockout) {
		return super.findList(stockout);
	}

	@Override
	public Page<Stockout> findPage(Page<Stockout> page, Stockout stockout) {
		return super.findPage(page, stockout);
	}

	@Override
	@Transactional(readOnly = false)
	public void save(Stockout stockout) {
		super.save(stockout);
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(Stockout stockout) {
		super.delete(stockout);
	}

	@Transactional(readOnly = false)
	public void saveStockoutSku(JSONArray skuList, String evidenceId) {
		try {
			JSONObject objectItem;
			StockoutSku stockoutSku;
			for (int i = 0; i < skuList.size(); i++) {
				objectItem = (JSONObject) skuList.get(i);
				stockoutSku = new StockoutSku();
				stockoutSku.setEvidenceId(evidenceId);
				stockoutSku.setAmount(Integer.parseInt(objectItem.getString("num")));
				stockoutSku.setSkuId(Integer.parseInt(objectItem.getString("skuId")));
				if (null != objectItem.getString("skuPrice")) {
					stockoutSku.setSkuPrice(BigDecimal.valueOf(objectItem.getDouble("skuPrice")));
				}
				stockoutSkuService.save(stockoutSku);
			}

		} catch (Exception e) {
			logger.error("Facade Error StockoutFacadeImpl -> save   " + e.getMessage());
			throw new ServiceException("保存异常");
		}
	}

	public void insertStockoutOrder(String orderId, String evidenceId) {
		stockoutMapper.insertStockoutOrder(orderId, evidenceId);
	}

	public void insertStockoutOrder(String serviceType, String serviceId, String evidenceId) {
		stockoutMapper.insertStockoutOrderWithType(serviceType, serviceId, evidenceId);
	}

	public List<String> findStockoutOrderByEid(String evidenceId) {
		return stockoutMapper.findStockoutOrderByEid(evidenceId);
	}

	public List<String> findMonthErrorStockoutOrderByEid(String evidenceId) {
		return stockoutMapper.findMonthErrorStockoutOrderByEid(evidenceId);
	}

	public List<String> findStockoutRepairByEid(String evidenceId) {
		return stockoutMapper.findStockoutRepairByEid(evidenceId);
	}

	public List<String> findMonthErrorStockoutRepairByEid(String evidenceId) {
		return stockoutMapper.findMonthErrorStockoutRepairByEid(evidenceId);
	}

	public Page<Stockout> findQcByPage(Page<Stockout> page, Stockout stockout) {
		dataRuleFilter(stockout);
		stockout.setPage(page);
		page.setList(mapper.findQcList(stockout));
		return page;
	}

	public Page<Stockout> findOutByPage(Page<Stockout> page, Stockout stockout) {
		dataRuleFilter(stockout);
		stockout.setPage(page);
		page.setList(mapper.findOutList(stockout));
		return page;
	}

	public void finishRepair(List<String> repairIds) throws Throwable {
		String ids = String.join(",", repairIds);
		final String contentType = "application/json";
		final String url = Global.getConfig("httpUrl") + "/sc/repair/finish?ids=" + ids + "&scMark=sc:"
				+ UserUtils.getUser().getNo();
		JSONObject req = new JSONObject();
		// req.put("ids", repairIds);
		// req.put("scMark", "sc:" + UserUtils.getUser().getNo());
		String resp = HttpUtils.post(url, req.toJSONString(), false, contentType);
		JSONObject respObj = JSON.parseObject(resp);
		if (respObj.getString("res").equals("0")) {
			throw new FacadeException("复壮完成失败");
		}
	}

	public void deleteRdOfSpec(String stockroomId) {
		stockoutMapper.deleteRdOfSpec(stockroomId);
	}

	public void deleteRdOfSpecConsist(String stockroomId) {
		stockoutMapper.deleteRdOfSpecConsist(stockroomId);
	}

	public void updateRepairOpState(String stockroomId) {
		stockoutMapper.updateRepairOpState(stockroomId);
	}

	public void updateStockoutState(String evidenceId, StockoutState stockoutState) {
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = null;
		if (StringUtils.equals(stockoutState.getType(), StockoutState.FINISH.getType())) {
			date = f.format(new Date());
		}
		stockoutMapper.updateStockoutState(evidenceId, stockoutState.getType(), date);
	}

	public void claim(String evidenceId) throws Throwable {
		final String contentType = "application/json";
		final String url = Global.getConfig("httpUrl") + "/sc/order/claim?evidenceId=" + evidenceId + "&scMark=sc:"
				+ UserUtils.getUser().getNo() + "&taskDefKey=STEP_BASE";
		JSONObject req = new JSONObject();
		req.put("evidenceId", evidenceId);
		req.put("taskDefKey", "STEP_BASE");
		req.put("scMark", "sc:" + UserUtils.getUser().getNo());
		String resp = HttpUtils.post(url, req.toJSONString(), false, contentType);

		logger.info("质检远程调用url: {}", url);
		JSONObject respObj = JSON.parseObject(resp);
		logger.info("质检远程返回: {}", respObj.toJSONString());

		if (respObj.getString("code").equals("3")) {
			throw new FacadeException("自动审批失败");
		}
	}

	public List<String> findRepairIdsByEids(List<String> eids) {
		return stockoutMapper.findRepairIdsByEids(eids);
	}

	public List<String> findCanFinishEids(String companyId) {
		return stockoutMapper.findCanFinishEids(companyId);
	}

	public Stockout findById(String id) {
		return stockoutMapper.findById(id);
	}
}
